package com.google.samples.apps.worker

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.work.*
import com.google.samples.apps.library_common.utils.LogUtils
import java.util.concurrent.TimeUnit


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
//https://zhuanlan.zhihu.com/p/78599394
        val inputData: Data = Data.Builder().putString("input_data", "Hello World!").build()

        val constraints = Constraints.Builder()
            .setRequiresCharging(true)
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .setRequiresBatteryNotLow(true)
            .build()


        val oneTimeWorkRequest = OneTimeWorkRequestBuilder<UploadLogWorker>()
            .setConstraints(constraints) // 设置触发条件
            .setInitialDelay(3, TimeUnit.SECONDS) //符合触发条件后，延迟3s执行
            .addTag("UploadTag") // 添加tag
            .setInputData(inputData)
            .build()

        WorkManager.getInstance(this).getWorkInfoByIdLiveData(oneTimeWorkRequest.getId())
            .observe(this@MainActivity,
                Observer<WorkInfo?> {
                    LogUtils.d("onChanged()-> workInfo:$it")
                })
        WorkManager.getInstance(this)
            .enqueue(oneTimeWorkRequest)

    }
}